package com.lilong.jwt.entity.user;

import com.google.common.collect.Lists;
import com.lilong.jwt.common.base.BaseEntity;
import lombok.Getter;
import lombok.Setter;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.util.ObjectUtils;

import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.util.*;


@Entity
@Getter
@Setter
@Table(name = "tu_user")
public class User extends BaseEntity implements UserDetails {
    /**
     * 用户名
     */
    @NotNull(message = "用户名"+NOT_NULL)
    private String username;
    /**
     * 密码
     */
    private String password;
    /**
     * 姓名
     */
    @NotNull(message = "用户姓名"+NOT_NULL)
    private String name;
    /**
     * 邮箱
     */
    @NotNull(message = "用户邮箱"+NOT_NULL)
    private String email;
    /**
     * 手机号
     */
    private String mobilePhone;
    /**
     * 备注
     */
    private String remark;

    /**
     * 用户状态 0 禁用 1启用 -1 删除
     */
    private Integer status;

    @ManyToMany(cascade = {CascadeType.REFRESH}, fetch = FetchType.LAZY)
    private List<Role> roles;

    @Transient
    private List<GrantedAuthority> grantedAuthorities;

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        List<GrantedAuthority> gas = new ArrayList<>();
        if(!ObjectUtils.isEmpty(this.getRoles()))
        {
            this.getRoles().forEach(r -> {
                if(!ObjectUtils.isEmpty(r.getPermissions())){
                    r.getPermissions().forEach(p -> {
                        if (!ObjectUtils.isEmpty(p.getUrl())) {
                            //1：此处将权限信息添加到 GrantedAuthority 对象中，在后面进行全权限验证时会使用GrantedAuthority 对象。
                            Lists.newArrayList(p.getUrl().split(",")).forEach(s -> gas.add(() -> s));
                        }
                    });
                }
            });
        }

        return gas;
    }


    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}
